package com.education.welco.controller.app;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.education.common.pojo.AjaxResult;
import com.education.common.pojo.TStudent;
import com.education.demouse.pojo.model.StudentAnswerDetails;
import com.education.demouse.service.IStudentAnswerDetailsService;
import com.education.websocket.data.HomeBuffer;
import com.education.websocket.data.HomeData;
import com.education.websocket.server.WebSocketServerWELCO;
import com.education.welco.pojo.*;
import com.education.welco.pojo.vo.OrderAnswerRES;
import com.education.welco.pojo.vo.QuestionParsingVo;
import com.education.welco.pojo.vo.UserPaperAnswerInfo;
import com.education.welco.service.*;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.education.common.core.BaseController.writeJSON;

/**
 * 试卷表
 *
 * @date 2021-03-04 15:45:18
 */
@RestController
@RequestMapping("/app/orderpaper")
public class AppOrderPaperController {

    @Autowired
    private ISysSourcePayService sysSourcePayService;
    @Autowired
    private OrderPaperService orderPaperService;
    @Autowired
    private OrderPaperQuestionService orderPaperQuestionService;
    @Autowired
    private OrderQuestionService orderQuestionService;
    @Autowired
    private OrderAnswerService orderAnswerService;
    @Autowired
    private OrderUserPaperService orderUserPaperService;
    @Autowired
    private ITStudentService studentService;
    @Autowired
    private ITTeacherService teacherService;
    @Autowired
    private ISCatalogMenuService catalogMenuService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private IStudentAnswerDetailsService studentAnswerDetailsService;
    @Autowired
    private OrderWrongAnswerService orderWrongAnswerService;
    @Autowired
    private HomeBuffer homeBuffer;


    //添加试卷
    @PostMapping("/addpaper")
    public void addparper(HttpServletResponse response, OrderPaper orderPaper) throws IOException {
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = dateFormat.format(date);
        orderPaper.setCreateTime(format);
        int paper = orderPaperService.insertOrderPaper(orderPaper);
        writeJSON(paper, response, "200", "添加成功");
    }

    //批量删除试卷
    @GetMapping("/deletepaper")
    public void deletequestion(HttpServletResponse response, OrderPaper orderPaper, String[] ids) throws IOException {
        writeJSON(orderPaperService.deleteOrderPaperByIds(ids), response, "200", "删除成功");
    }

    //修改试卷
    @PostMapping("/updatepaper")
    public void updatequestion(HttpServletResponse response, OrderPaper orderPaper) throws IOException {
        Integer id = orderPaper.getId();
        if (id != null) {
            writeJSON(orderPaperService.updateOrderPaper(orderPaper), response, "200", "修改成功");
        } else {
            writeJSON(null, response, "201", "输入错误");
        }
    }

    /**
     * 查询试卷列表(未作答)   -查询试卷列表（0未答题 1已批阅  2未批阅）  已回答，  未回答
     *
     * @param lessonIdTop 课程0级id  找所有的二级目录
     * @param lessonIdTwo 课程2级id  二级目录
     * @param classId     班级id
     * @param courseId    课程id
     * @param stuId       学生用户id
     * @throws IOException
     */
    @GetMapping("/selectlist")
    public AjaxResult selectquestionlist(@RequestParam(value = "lessonIdTop", required = true) Integer lessonIdTop,
                                         @RequestParam(value = "lessonIdTwo", required = false) Integer lessonIdTwo,
                                         @RequestParam(value = "classId", required = false) Integer classId,
                                         @RequestParam(value = "courseId", required = false) String courseId,
                                         @RequestParam(value = "stuId", required = false) Integer stuId) {

        //获取二级目录集合
        List<SCatalogMenu> TwoCataList = selectTwoList(lessonIdTop);
        //流转换对象
        List<Integer> twoIntList = TwoCataList.stream().map(a -> a.getId()).collect(Collectors.toList());

        //查学生回答了的试题  （二级目录id、班级id、用户id） 试卷表
        OrderPaper orderPaper = new OrderPaper();
        orderPaper.setStuId(stuId);
        orderPaper.setTwoIDList(twoIntList);
        //orderPaper.setClassId(classId);//逻辑弃用
        List<OrderPaper> orderPaperList = orderPaperService.selectOrderPaperStuList(orderPaper);

        /*//全部列表int
        List<Integer> orderPaperListAll = orderPaperService.selectOrderPaperStuListAll(orderPaper);
        //已提交的作业id
        List<Integer> orderPaperListSome = orderPaperService.selectOrderPaperStuListSome(courseId, stuId);
        //找出为做作业的作业
        List<Integer> other = new ArrayList<>();
        for (Integer all : orderPaperListAll) {
            if (!orderPaperListSome.contains(all)) {
                other.add(all);
            }
        }
        //根据otherlist 查寻未提交作业
        if (other.size() > 0) {
            List<OrderPaper> orderPaperListOther = orderPaperService.selectOrderPaperStuListOther(other);
            orderPaperList.addAll(orderPaperListOther);
        }*/

        //lessonIdTwo  进而确定是查全部列表还是某个二级目录下
        if (null != lessonIdTwo) {
            //map过滤
            List<OrderPaper> collect = orderPaperList.stream().filter(aaa -> aaa.getCatalogId().equals(String.valueOf(lessonIdTwo))).collect(Collectors.toList());
            PageInfo<OrderPaper> objectPageInfo = new PageInfo<>(collect);
            return AjaxResult.success(objectPageInfo);
        }

        PageInfo<OrderPaper> objectPageInfo = new PageInfo<>(orderPaperList);
        return AjaxResult.success(objectPageInfo);
    }

    public List<SCatalogMenu> selectTwoList(Integer lessonId) {
        SCatalogMenu sCatalogMenu = new SCatalogMenu();
        //查询出第1级列表
        sCatalogMenu.setParentId(0);
        sCatalogMenu.setId(lessonId);
        SCatalogMenu list = catalogMenuService.selectSCatalogMenuList2(sCatalogMenu);
        //二级 以及 下面子列表
        return listSon2(list);
    }

    //查询目录列表
    public List<SCatalogMenu> listSon2(SCatalogMenu cList) {
        //根据课程id查询出一级目录列表jrCatalogs
        List<SCatalogMenu> jrCatalogs = catalogMenuService.selectSCatalogMenuByParentId(cList.getId());
        if (jrCatalogs != null && jrCatalogs.size() > 0) {
            //cList.setChildren(listSon(jrCatalogs));
            return listSon(jrCatalogs);
        }
        return null;
    }

    public List<SCatalogMenu> listSon(List<SCatalogMenu> cList) {
        List<SCatalogMenu> twoSCatalogMenu = new ArrayList<>();
        for (SCatalogMenu catalogMenu : cList) {
            //根据第一级的id查询出二级列表
            List<SCatalogMenu> jrCatalogs = catalogMenuService.selectSCatalogMenuByParentId(catalogMenu.getId());
            //二级列表汇总
            twoSCatalogMenu.addAll(jrCatalogs);
            if (jrCatalogs != null && jrCatalogs.size() > 0) {
                //设置子级集合
                //catalogMenu.setChildren(listSon(jrCatalogs));
                //catalogMenu.setChildren(jrCatalogs);
            }
        }
        return twoSCatalogMenu;
    }

    //查询试卷试题详情   -试题列表进入答题接口 （查询该试卷的试题）
    @GetMapping("/selectquestionlist")
    public AjaxResult selectpaperquestionlist(@RequestParam(value = "paperId", required = false) Integer paperId,
                                              @RequestParam(value = "userId", required = false) Integer userId) {
        OrderPaperQuestion orderPaperQuestion = new OrderPaperQuestion();
        orderPaperQuestion.setPaperId(paperId);
        List<OrderQuestion> arrayList = new ArrayList<>();
        HashMap<String, Object> map = new HashMap<>();
        //试卷试题关联表
        List<OrderPaperQuestion> orderPaperQuestions = orderPaperQuestionService.selectOrderPaperQuestionList(orderPaperQuestion);
        //根据试题id查找试题
        for (OrderPaperQuestion orderPaperQuestion1 : orderPaperQuestions) {
            Integer questionId = orderPaperQuestion1.getQuestionId();
            OrderQuestion orderQuestion = orderQuestionService.selectOrderQuestionById(questionId);
            arrayList.add(orderQuestion);
        }
        //试题设置当前用户是否收藏标识
        List<OrderQuestion> list = setQuestionIsCollection(arrayList, userId, "1");

        //map.put("quesList", arrayList);
        map.put("quesList", list);

        return AjaxResult.success(map);
    }

    /**
     * 试题设置是否收藏标识-试题列表
     */
    private List<OrderQuestion> setQuestionIsCollection(List<OrderQuestion> checkedQuestionList, Integer userId, String type) {
        SysSourcePay sourcePay = new SysSourcePay();
        sourcePay.setCUserId(userId);
        sourcePay.setNIsCollection(1);//StatusEnum.ONE.value
        sourcePay.setCResourceType("2");//StatusEnum.TWO.type
        List<SysSourcePay> sysSourcePays = sysSourcePayService.selectSysSourcePayList(sourcePay);
        if (sysSourcePays.size() > 0) {
            //该用户收藏的试题id数组
            List<Integer> collect = sysSourcePays.stream().map(SysSourcePay::getCResourceId).collect(Collectors.toList());
            if ("1".equals(type)) {
                List<OrderQuestion> resultList = new ArrayList<>(checkedQuestionList.size());
                for (int i = 0; i < checkedQuestionList.size(); i++) {
                    OrderQuestion sysOrderQuestion = JSON.parseObject(JSON.toJSONString(checkedQuestionList.get(i)), OrderQuestion.class);
                    if (collect.contains(sysOrderQuestion.getId())) {
                        sysOrderQuestion.setIsCollection("1");
                    }
                    resultList.add(sysOrderQuestion);
                }
                return resultList;
            } else {
                for (OrderQuestion sysOrderQuestion : checkedQuestionList) {
                    if (collect.contains(sysOrderQuestion.getId())) {
                        sysOrderQuestion.setIsCollection("1");
                    }
                }
                return checkedQuestionList;
            }
        }
        return checkedQuestionList;
    }

    /**
     * 试题设置是否收藏标识-试题解析列表
     */
    private List<QuestionParsingVo> setQuestionIsCollection2(List<QuestionParsingVo> checkedQuestionList, Integer userId, String type) {
        SysSourcePay sourcePay = new SysSourcePay();
        sourcePay.setCUserId(userId);
        sourcePay.setNIsCollection(1);//StatusEnum.ONE.value
        sourcePay.setCResourceType("2");//StatusEnum.TWO.type
        List<SysSourcePay> sysSourcePays = sysSourcePayService.selectSysSourcePayList(sourcePay);
        if (sysSourcePays.size() > 0) {
            //该用户收藏的试题id数组
            List<Integer> collect = sysSourcePays.stream().map(SysSourcePay::getCResourceId).collect(Collectors.toList());
            if ("1".equals(type)) {
                List<QuestionParsingVo> resultList = new ArrayList<>(checkedQuestionList.size());
                for (int i = 0; i < checkedQuestionList.size(); i++) {
                    QuestionParsingVo sysOrderQuestion = JSON.parseObject(JSON.toJSONString(checkedQuestionList.get(i)), QuestionParsingVo.class);
                    if (collect.contains(sysOrderQuestion.getId())) {
                        sysOrderQuestion.setIsCollection("1");
                    }
                    resultList.add(sysOrderQuestion);
                }
                return resultList;
            } else {
                for (QuestionParsingVo sysOrderQuestion : checkedQuestionList) {
                    if (collect.contains(sysOrderQuestion.getId())) {
                        sysOrderQuestion.setIsCollection("1");
                    }
                }
                return checkedQuestionList;
            }
        }
        return checkedQuestionList;
    }

    //答题   -试卷回答完毕答题接口

    /**
     * 对象中包括的属性：试题的全部信息
     * //试题id
     * private Integer questionId;
     * //答卷人id
     * private Integer userId;
     * //学生答案
     * private String answer;
     * //标准正确答案
     * private String stanswer;
     * //试题类型  (1 单选 2 判断 3 多选 4 简答)
     * private Integer type;
     * //试卷id
     * private Integer paperId;
     * //课堂id
     * private Integer courseId;
     * //考试用时
     * private Integer examTime;
     *
     * @param json
     * @return
     * @throws IOException
     */
    @PostMapping("/answers")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult answer(String json) throws IOException {
        //接收答题参数并转换
        OrderAnswerRES orderAnswerRES = JSON.parseObject(json, OrderAnswerRES.class);

        List<OrderAnswer> orderAnswers = orderAnswerRES.getOrderAnswerList();
        //准备参数
        Integer paperId = orderAnswerRES.getPaperId();
        Integer userId = orderAnswerRES.getUserId();
        Integer courseId = orderAnswerRES.getCourseId();
        String examTime = orderAnswerRES.getExamTime();
        OrderUserPaper orderUserPaper2 = orderUserPaperService.SelectOrderUserPaper(paperId, userId);
        if (orderUserPaper2 != null) {
            return AjaxResult.error("已提交！");
        }
        //添加该答题者该套试卷最新记录    试卷回答表  试卷id与课堂id
        int oupId = 0;//接收新增后返回的主键id
        OrderUserPaper orderUserPaper = new OrderUserPaper();
        orderUserPaper.setPaperId(paperId);
        orderUserPaper.setUserId(userId.toString());
        orderUserPaper.setCourseId(courseId);
        TStudent selectstudent = studentService.selectTStudentById2(userId);
        if (selectstudent != null) {
            String studentSex = selectstudent.getStudentSex();
            String studentName = selectstudent.getStudentName();
            orderUserPaper.setUserName(studentName);
            orderUserPaper.setStudentSex(studentSex);
            orderUserPaperService.InsertOrderPaper(orderUserPaper);
            oupId = orderUserPaper.getId();
        }

        //添加学生答案  试题回答表添加用户回答   userpaperid和创建时间
        for (OrderAnswer orderAnswer : orderAnswers) {
            orderAnswer.setPaperId(paperId);
            orderAnswer.setUserId(userId);
            orderAnswer.setUserPaperId(oupId);
            orderAnswer.setCreateTime(new Date());
            orderAnswerService.insertOrderAnswer(orderAnswer);
        }

        //准备客观题评分的内容      同时准备答题结果对象
        OrderPaper orderPaper = orderPaperService.selectOrderPaperById(paperId);//得到试卷的具体情况
        //得到该套试卷各种题型相应的分数
        String score = orderPaper.getScore();//试卷满分
        Integer singleNum = Integer.valueOf(orderPaper.getSingle());
        Integer singleScore = Integer.valueOf(orderPaper.getSingleScore());
        Integer judgementNum = Integer.valueOf(orderPaper.getJudgment());
        Integer judgmentScore = Integer.valueOf(orderPaper.getJudgmentScore());
        Integer manyNum = Integer.valueOf(orderPaper.getMany());
        Integer manyScore = Integer.valueOf(orderPaper.getManyScore());
        //简答题数量
        Integer answNum = Integer.valueOf(orderPaper.getAnsw());
        String introductionName = orderPaper.getIntroduction();

        //单选正确 错误 未做
        int correctdanxuan = 0;
        int errordanxuan = 0;
        int correctpanduan = 0;
        int errorpanduan = 0;
        int correctduoxuan = 0;
        int errorduoxuan = 0;
        //简答回答数
        int shortAns = 0;
        //未回答数量
        //int notAns = 0;

        //准备返回数据：   试卷名称、报告生成时间、 正确率、  【考试用时间】   总答题/未答题  题型具体回答情况
        Map<String, Object> answerResult = new HashMap<>();//初始化答题的结果

        //系统评分开始  循环开始
        for (OrderAnswer orderAnswer : orderAnswers) {
            //学生回答答案
            String answer1 = orderAnswer.getAnswer();
            //标准正确答案
            String stanswer = orderAnswer.getStanswer();
            //试题类型
            Integer type = orderAnswer.getType();
            //单选
            if (type.equals(1)) {
                if (StringUtils.isNotBlank(answer1)) {
                    if (answer1.equals(stanswer)) {
                        correctdanxuan += 1;
                        //若相等，则填入该题相应的分数 回答正确
                        orderAnswer.setPaperId(paperId);
                        orderAnswer.setUserId(userId);
                        orderAnswer.setScore(singleScore);
                        orderAnswer.setIsCorrect(1);
                        orderAnswerService.updateOrderAnswer1(orderAnswer);
                    } else {  //回答错误
                        errordanxuan += 1;
                        orderAnswer.setPaperId(paperId);
                        orderAnswer.setUserId(userId);
                        orderAnswer.setScore(0);
                        orderAnswer.setIsCorrect(0);
                        orderAnswerService.updateOrderAnswer1(orderAnswer);
                    }
                } else {
                    //notAns += 1;
                    orderAnswer.setPaperId(paperId);
                    orderAnswer.setUserId(userId);
                    orderAnswer.setScore(0);
                    orderAnswer.setIsCorrect(2);
                    orderAnswerService.updateOrderAnswer1(orderAnswer);
                }
            }
            //判断
            else if (type.equals(2)) {
                if (StringUtils.isNotBlank(answer1)) {
                    if (answer1.equals(stanswer)) {
                        correctpanduan += 1;
                        //若相等，则填入该题相应的分数
                        orderAnswer.setPaperId(paperId);
                        orderAnswer.setUserId(userId);
                        orderAnswer.setScore(judgmentScore);
                        orderAnswer.setIsCorrect(1);
                        orderAnswerService.updateOrderAnswer1(orderAnswer);
                    } else {
                        errorpanduan += 1;
                        orderAnswer.setPaperId(paperId);
                        orderAnswer.setUserId(userId);
                        orderAnswer.setScore(0);
                        orderAnswer.setIsCorrect(0);
                        orderAnswerService.updateOrderAnswer1(orderAnswer);
                    }
                } else {
                    //notAns += 1;
                    orderAnswer.setPaperId(paperId);
                    orderAnswer.setUserId(userId);
                    orderAnswer.setScore(0);
                    orderAnswer.setIsCorrect(2);
                    orderAnswerService.updateOrderAnswer1(orderAnswer);
                }
            }
            //多选
            else if (type.equals(3)) {
                if (StringUtils.isNotBlank(answer1)) {
                    String[] split = answer1.split(",");
                    String[] split1 = stanswer.split(",");
                    Arrays.sort(split);
                    Arrays.sort(split1);
                    if (Arrays.equals(split, split1)) {
                        correctduoxuan += 1;
                        //若相等，则填入该题相应的分数
                        orderAnswer.setPaperId(paperId);
                        orderAnswer.setUserId(userId);
                        orderAnswer.setScore(manyScore);
                        orderAnswer.setIsCorrect(1);
                        orderAnswerService.updateOrderAnswer1(orderAnswer);
                    } else {
                        errorduoxuan += 1;
                        orderAnswer.setPaperId(paperId);
                        orderAnswer.setUserId(userId);
                        orderAnswer.setScore(0);
                        orderAnswer.setIsCorrect(0);
                        orderAnswerService.updateOrderAnswer1(orderAnswer);
                    }
                } else {
                    //notAns += 1;
                    orderAnswer.setPaperId(paperId);
                    orderAnswer.setUserId(userId);
                    orderAnswer.setScore(0);
                    orderAnswer.setIsCorrect(2);
                    orderAnswerService.updateOrderAnswer1(orderAnswer);
                }
            }
            //简答题
            else if (type.equals(4)) {
                //学生回答答案不为空，代表此简答题已做
                if (StringUtils.isNotBlank(answer1)) {
                    shortAns += 1;
                    orderAnswer.setPaperId(paperId);
                    orderAnswer.setUserId(userId);
                    orderAnswer.setScore(0);
                    orderAnswer.setIsCorrect(0);
                    orderAnswerService.updateOrderAnswer1(orderAnswer);
                } else {
                    //notAns += 1;
                    orderAnswer.setPaperId(paperId);
                    orderAnswer.setUserId(userId);
                    orderAnswer.setScore(0);
                    orderAnswer.setIsCorrect(2);
                    orderAnswerService.updateOrderAnswer1(orderAnswer);
                }
            }
        }//循环结束

        UserPaperAnswerInfo userPaperAnswerInfo = new UserPaperAnswerInfo();
        //试卷名称
        userPaperAnswerInfo.setPaperName(introductionName);
        //报告生成时间
        userPaperAnswerInfo.setGenerateTime(new Date());
        //1.客观题正确率
        double correctRate = (double) (correctdanxuan + correctpanduan + correctduoxuan) / (double) (singleNum + judgementNum + manyNum);
        String a_str = String.format("%.2f", correctRate);
        userPaperAnswerInfo.setCorrectRate(a_str);
        //2.考试用时 examTime
        userPaperAnswerInfo.setExamTimeSeconds(Integer.valueOf(examTime));
        userPaperAnswerInfo.setExamTime(timeStampToDhms(Long.valueOf(examTime)));
        //3.总答题/未答题
        //全部回答的题
        int answerAll = correctdanxuan + correctpanduan + correctduoxuan + errordanxuan + errorpanduan + errorduoxuan + shortAns;
        //全部回答的题(除去主观题)
        int answerAllDivideAns = correctdanxuan + correctpanduan + correctduoxuan + errordanxuan + errorpanduan + errorduoxuan;
        //试卷全部的题
        int allNum = singleNum + judgementNum + manyNum + answNum;
        //试卷全部的题(除去主观题)
        int allNumDivideAns = singleNum + judgementNum + manyNum;
        int noNum = allNum - answerAll;//试卷未回答的题
        //试卷未回答的题(除去主观题)
        int noNumDivideAns = allNumDivideAns - answerAllDivideAns;
        //4.客观题得分情况
        int objectiveItemScore = (correctdanxuan * singleScore) + (correctpanduan * judgmentScore) + (correctduoxuan * manyScore);
        userPaperAnswerInfo.setAnswerAll(answerAll);
        userPaperAnswerInfo.setAllNum(allNum);
        //具体题型情况
        //单选情形
        userPaperAnswerInfo.setCorrectdanxuan(correctdanxuan);
        userPaperAnswerInfo.setErrordanxuan(errordanxuan);
        //判断情形
        userPaperAnswerInfo.setCorrectpanduan(correctpanduan);
        userPaperAnswerInfo.setErrorpanduan(errorpanduan);
        //多选情形
        userPaperAnswerInfo.setCorrectduoxuan(correctduoxuan);
        userPaperAnswerInfo.setErrorduoxuan(errorduoxuan);
        //试题总分
        userPaperAnswerInfo.setTotalper(score);
        //共答对数量
        int totalCorrect = correctdanxuan + correctpanduan + correctduoxuan;
        userPaperAnswerInfo.setTotalCorrect(totalCorrect);
        //共答错数量 totalError   目前默认简答题回答是错误的
        int totalError = errordanxuan + errorpanduan + errorduoxuan + answNum;
        userPaperAnswerInfo.setTotalError(totalError);
        ////共未答数量 totalNotAns
        userPaperAnswerInfo.setTotalNotAns(noNum);

        //准备对象json格式化
        String userPaperAnswerInfoString = JSON.toJSONString(userPaperAnswerInfo);

        //试卷回答表加一个字段   存贮答题详情对象  更新客观题分数objectiveItemScore
        OrderUserPaper orderUserPaper1 = new OrderUserPaper();
        orderUserPaper1.setPaperId(paperId);
        orderUserPaper1.setUserId(String.valueOf(userId));
        orderUserPaper1.setScore(String.valueOf(objectiveItemScore));
        orderUserPaper1.setUserPaperInfo(userPaperAnswerInfoString);
        orderUserPaper1.setDuration(Integer.valueOf(examTime));
        orderUserPaper1.setAllNum(allNum);
        orderUserPaper1.setAnswerAll(answerAll);
        orderUserPaper1.setTotalCorrect(totalCorrect);
        orderUserPaper1.setTotalError(totalError);
        orderUserPaper1.setTotalNotAns(noNum);
        orderUserPaper1.setCorrectRate(new BigDecimal(a_str));
        orderUserPaper1.setPaperName(introductionName);
        int update = orderUserPaperService.update(orderUserPaper1);

        /**
         * websocket数据更新-学生提交试卷后带批阅试卷数量加1
         * 根据courseId得到老师的userid
         */
        String teaUserId = orderUserPaperService.selectTeaIdByCourseId(courseId);
        Object res = redisTemplate.opsForValue().get("wait:data:" + teaUserId);
        if (Objects.nonNull(res)) {
            HomeData homeData = (HomeData) res;
            homeData.setPaperWait(homeData.getPaperWait() + 1);
            redisTemplate.opsForValue().set("wait:data:" + teaUserId, homeData);
            WebSocketServerWELCO.sendInfo(homeData, teaUserId);
        } else {
            //数据初始化
            Object data = homeBuffer.data(String.valueOf(teaUserId));
            HomeData homeData = (HomeData) data;
            homeData.setPaperWait(homeData.getPaperWait() + 1);
            redisTemplate.opsForValue().set("wait:data:" + teaUserId, homeData);
            WebSocketServerWELCO.sendInfo(homeData, String.valueOf(teaUserId));
        }

        //ToDo demo演示中提供的业务逻辑
        //试卷信息 学生信息(班级) 老师信息
        OrderPaper orderPaperInfo = orderPaperService.selectOrderPaperById(paperId);//试卷信息
        TStudent studentInfo = studentService.queryStudentAndClassByStuUserId(userId);//学生信息
        TTeacher tTeacher = teacherService.selectTTeacherById1(Integer.valueOf(orderPaperInfo.getCreateuser()));//老师信息
        StudentAnswerDetails studentAnswerDetails = new StudentAnswerDetails();
        studentAnswerDetails.setPaperId(paperId);
        studentAnswerDetails.setPaperName(orderPaperInfo.getIntroduction());
        studentAnswerDetails.setPaperScore(Double.valueOf(String.valueOf(objectiveItemScore)));
        studentAnswerDetails.setStuUserId(studentInfo.getUserId());
        studentAnswerDetails.setStuUserName(studentInfo.getStudentName());
        studentAnswerDetails.setClassId(studentInfo.getClassId());
        studentAnswerDetails.setClassName(studentInfo.getClassName());
        studentAnswerDetails.setTeaUserId(Integer.valueOf(orderPaperInfo.getCreateuser()));
        studentAnswerDetails.setTeaUserName(tTeacher.getTeacherName());
        studentAnswerDetails.setFullScore(Double.valueOf(orderPaperInfo.getScore()));

        studentAnswerDetailsService.insertStudentAnswerDetails(studentAnswerDetails);

        // 加入错题本
        orderWrongAnswerService.insertBatch(userId, paperId);
        return AjaxResult.success(userPaperAnswerInfo);
    }


    /**
     * 答题完毕后学生查看答题详情
     *
     * @param paperId 试卷id
     * @param stuId   学生用户id
     * @return
     */
    @GetMapping("/exitQuerypaperInfo")
    public AjaxResult exitQuerypaperInfo(@RequestParam(value = "paperId", required = false) Integer paperId,
                                         @RequestParam(value = "stuId", required = false) Integer stuId) {

        OrderUserPaper orderUserPaper = orderUserPaperService.exitQuerypaperInfo(paperId, stuId);
        UserPaperAnswerInfo userPaperAnswerInfo = new UserPaperAnswerInfo();
        if (StringUtils.isNotBlank(orderUserPaper.getUserPaperInfo())) {
            userPaperAnswerInfo = JSONObject.parseObject(orderUserPaper.getUserPaperInfo(), UserPaperAnswerInfo.class);
        }
        return AjaxResult.success(userPaperAnswerInfo);
    }


    /**
     * 老师端首页成绩排行  班级与试卷
     *
     * @param paperId
     * @param teaId
     * @param classId
     * @return
     */
    @GetMapping("/homeScoreQueryForTea")
    public AjaxResult homeScoreQueryForTea(@RequestParam(value = "paperId", required = false) Integer paperId,
                                           @RequestParam(value = "teaId", required = false) Integer teaId,
                                           @RequestParam(value = "classId", required = false) Integer classId) {

        List<OrderUserPaper> orderUserPaperList = orderUserPaperService.homeScoreQueryForTea(teaId, paperId, classId);
        return AjaxResult.success(orderUserPaperList);
    }


    /**
     * 老师端首页成绩排行 查找班级下的试卷列表
     */
    @GetMapping("/selectPaperBoxByClassId")
    public AjaxResult selectPaperBoxByClassId(@RequestParam(value = "classId", required = false) Integer classId) {

        List<OrderPaper> orderPaperList = orderUserPaperService.selectPaperBoxByClassId(classId);
        return AjaxResult.success(orderPaperList);
    }


    /**
     * 毫秒转换为时间字符串
     *
     * @param milliseconds
     * @return
     */
    public static String timeStampToDhms(long milliseconds) {
        long day = TimeUnit.MILLISECONDS.toDays(milliseconds);
        long hours = TimeUnit.MILLISECONDS.toHours(milliseconds) - TimeUnit.DAYS.toHours(TimeUnit.MILLISECONDS.toDays(milliseconds));
        long minutes = TimeUnit.MILLISECONDS.toMinutes(milliseconds) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(milliseconds));
        long seconds = TimeUnit.MILLISECONDS.toSeconds(milliseconds) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(milliseconds));
        StringBuilder sb = new StringBuilder();
        if (day != 0) {
            sb.append(day + "天");
        }
        sb.append(hours + "小时");
        sb.append(minutes + "分");
        sb.append(seconds + "秒");
        return sb.toString();
    }

    /**
     * 答题试卷列表    -成绩查询列表  查看试卷答题详情
     *
     * @param paperId 试卷id
     * @param userId  学生用户id
     * @return
     */
    @GetMapping("/AnswerPapers")
    public AjaxResult AnswerPapers(@RequestParam(value = "paperId", required = false) Integer paperId,
                                   @RequestParam(value = "userId", required = false) Integer userId) {
        OrderUserPaper orderUserPaper = orderUserPaperService.SelectOrderUserPaperForInfo(paperId, userId);
        String userPaperInfo = orderUserPaper.getUserPaperInfo();
        UserPaperAnswerInfo userPaperAnswerInfo = JSONObject.parseObject(userPaperInfo, UserPaperAnswerInfo.class);
        return AjaxResult.success(userPaperAnswerInfo);
    }

    //成绩查询     -查看试卷答题详情  (试题解析-全部试题、错题) paperId=3&userId=1200

    /**
     * @param paperId
     * @param userId
     * @param filterType 1查全部 2查错误
     * @return
     */
    @GetMapping("/resultInquiry")
    public AjaxResult resultInquiry(@RequestParam(value = "paperId", required = false) Integer paperId,
                                    @RequestParam(value = "userId", required = false) Integer userId,
                                    @RequestParam(value = "filterType", required = false) Integer filterType) {
        //liftsail.top
        List<QuestionParsingVo> questionParsingVoList = orderAnswerService.selectQuestionParsing(paperId, userId);
        //试题设置当前用户是否收藏标识
        questionParsingVoList = setQuestionIsCollection2(questionParsingVoList, userId, "1");
        //试题解析-全部试题、错题   过滤剩下做错的
        if (filterType == 2) {
            questionParsingVoList = questionParsingVoList.stream().filter(questionParsingVo -> !questionParsingVo.getIsCorrect().equals("1")).collect(Collectors.toList());
        }
        PageInfo<QuestionParsingVo> objectPageInfo = new PageInfo<>(questionParsingVoList);
        return AjaxResult.success(objectPageInfo);
    }

    //成绩列表评语查询
    @GetMapping("/selectcomment")
    public AjaxResult selectcomment(Integer paperId, Integer userId) {
        OrderUserPaper orderUserPaper = orderUserPaperService.SelectOrderUserPaper(paperId, userId);
        return AjaxResult.success(orderUserPaper);
    }

    public static void main(String[] args) {
        UserPaperAnswerInfo userPaperAnswerInfo = new UserPaperAnswerInfo();
        //试卷名称
        userPaperAnswerInfo.setPaperName("试卷名称");
        //报告生成时间
        userPaperAnswerInfo.setGenerateTime(new Date());
        //1.客观题正确率

        userPaperAnswerInfo.setCorrectRate("88.89%");
        //2.考试用时 examTime
        userPaperAnswerInfo.setExamTime("10分20秒");
        //3.总答题/未答题
        userPaperAnswerInfo.setAnswerAll(18);
        userPaperAnswerInfo.setAllNum(20);
        //具体题型情况
        //单选情形
        userPaperAnswerInfo.setCorrectdanxuan(2);
        userPaperAnswerInfo.setErrordanxuan(1);
        //判断情形
        userPaperAnswerInfo.setCorrectpanduan(3);
        userPaperAnswerInfo.setErrorpanduan(2);
        //多选情形
        userPaperAnswerInfo.setCorrectduoxuan(3);
        userPaperAnswerInfo.setErrorduoxuan(1);

        //准备对象json格式化
        String userPaperAnswerInfoString = JSON.toJSONString(userPaperAnswerInfo);
        System.out.println(userPaperAnswerInfoString);
    }

}



